import aiohttp
from bs4 import BeautifulSoup
import requests
import base64

from Modules.db_commnads import insert_genre

header = {
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36"
}


async def check_url_img(url: str):
    try:
        if requests.get(url.replace("background-image: url('", "").replace("')", ""), headers=header).status_code == 200:
            return url.replace("background-image: url('", "").replace("')", "")
        else:
            return None
    except:
        url = "https:" + url.replace("background-image: url('", "").replace("')", "")
        return url


async def check_url(url: str):
    try:
        if requests.get(url, headers=header).status_code == 200:
            return url
        else:
            return None
    except:
        return None


async def parse_genres(url: str) -> list:
    list_data: list = []
    async with aiohttp.ClientSession() as session:
        response = await session.get(url=url, headers=header)
        soup = BeautifulSoup(await response.text(), 'lxml')
        items = soup.find_all('li', class_='album-item')
        for item in items:
            genre_url = await check_url(url.replace('/genres', '') + item.find('a').get('href'))
            genre_img = await check_url_img(item.find('span', class_='album-image').get('style'))
            if genre_url is not None:
                data = {
                    'name': ' '.join(item.find('span', class_='album-title').text.replace('\n', '').split()),
                    'url': genre_url,
                    'img': genre_img if genre_img is not None else 'NULL'
                }
                insert_genre(data)
                list_data.append(data)
    return list_data

